package nirvana.core.properties;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.Properties;

/**
 * YamlPropertySourceFactory
 *
 * @author linkanyway
 * @version 1.0
 * @date 2022/04/06 15:21
 */
@Slf4j
public class YamlPropertySourceFactory implements PropertySourceFactory {

    /**
     * 创建PropertySource
     * {@link PropertySource}
     *
     * @param name
     * @param encodedResource
     * @throws IOException
     */
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        String resourceName = Optional.ofNullable (name).orElse (encodedResource.getResource ().getFilename ());
        if (!resourceName.contains (".")) {
            log.error ("没有发现文件格式的源头【没有发现.】输入值为: " + resourceName);
            throw new FileNotFoundException ("没有发现文件格式的源头【没有发现.】");
        }
        if (resourceName.endsWith (".yml") || resourceName.endsWith (".yaml")) {
            List<PropertySource<?>> yamlSources = new YamlPropertySourceLoader ().load (resourceName,
                    encodedResource.getResource ());
            return yamlSources.get (0);
        }
        //保持支持Properties
        if (resourceName.endsWith (".properties")) {
            return new DefaultPropertySourceFactory ().createPropertySource (name, encodedResource);
        } else {//返回空的Properties
            return new PropertiesPropertySource (resourceName, new Properties ());
        }
    }

}